<template>
  <el-form :rules='loginRules' ref='loginForm' :model='loginForm' label-width='0'>
    <el-form-item prop='username'>
      <el-input @keyup.enter.native='handleLogin' v-model='loginForm.username' auto-complete='on' placeholder='请输入用户名'>
        <i slot='prefix' class='iconfont icon-shedu-yonghu'></i>
      </el-input>
    </el-form-item>
    <el-form-item prop='password'>
      <el-input  @keyup.enter.native='handleLogin' :type='passwordType' v-model='loginForm.password' auto-complete='on' placeholder='请输入密码'>
        <i class='el-icon-view el-input-icon' slot='suffix' @click='showPassword'></i>
        <i slot='prefix' class='iconfont icon-shedu-iconfonticon-mima'></i>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
    </el-form-item>
  </el-form>
</template>
<script>
  export default {
    name: 'userlogin',
    data() {
      const validatePassword = (rule, value, callback) => {
        if (value.length < 5) {
          callback(new Error('密码不能少于5位'))
        } else {
          callback()
        }
      }
      return {
        loginForm: { username: 'admin', password: 'admin', type: 'account' },
        loginRules: {
          username: [{ required: true, message: '请输入账号', trigger: 'change' }],
          password: [{ required: true, trigger: 'blur', validator: validatePassword }]
        },
        passwordType: 'password',
        loading:false
      }
    },
    methods: {
      showPassword() {
        this.passwordType === ''
          ? (this.passwordType = 'password')
          : (this.passwordType = '')
      },
      handleLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true
            this.$store.dispatch('LoginByUsername', this.loginForm).then(() => {
              this.loading = false
              this.$router.push({ path: '/' })
            }).catch(() => {
              this.loading = false
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    }
  }
</script>
